﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using SpicIE;

namespace AutoFillPluginIE
{
    class AutoFillSender
    {
        #region Constant

        public const int REQUESTFIELD = 1122;
        public const int RESPONSEFIELD = 1127;
        public const char SEPERATOR_CHAR = '$';
        public const int PORT = 7777;

        #endregion
        //public static String message = "";
        public static ArrayList messages = null;
        public static String url = "";
        public static bool isSubmit= false;
        public static void SendMessage()
        {
            byte[] bytes = new byte[1024];
            try
            {
                
                IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
                IPAddress ipAddress = ipHostInfo.AddressList[0];
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, PORT);
                Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //sender.ReceiveTimeout = 50000;
                
                try
                {
                    sender.Connect(remoteEP);
                    //Console.WriteLine("Socket connected to {0} ", sender.RemoteEndPoint.ToString());
                    String requestString = "0"+ SEPERATOR_CHAR+ AutoFillSender.REQUESTFIELD + SEPERATOR_CHAR.ToString() + messages.Count.ToString();
                    for (int i = 0; i < messages.Count; i++)
                    {
                        requestString += SEPERATOR_CHAR.ToString() + messages[i];
                    }
                    byte[] msg = Encoding.ASCII.GetBytes(requestString + "<EOF>");                    
                    int byteSent = sender.Send(msg);

                    // get Message                    
                    int byteRec = sender.Receive(bytes);                                        
                    
                    String str = Encoding.ASCII.GetString(bytes, 0, byteRec);
                    String[] msgs = str.Split(SEPERATOR_CHAR);
                    if (msgs == null)
                    {
                        MessageBox.Show("the message is null");
                        return;
                    }
                     
                    SHDocVw.IWebBrowser2 browser = AutoFillPluginIE.HostInstance.BrowserRef as SHDocVw.IWebBrowser2;
                    if (browser != null)
                    {
                        if (browser.LocationURL != url)
                        {
                            MessageBox.Show("The url is different. Can not fill data here");
                            return;
                        }
                        // get the IHTMLDocument interface
                        mshtml.IHTMLDocument2 htmlDoc = browser.Document as mshtml.IHTMLDocument2;
                        mshtml.HTMLDocument htmlDoc2 = browser.Document as mshtml.HTMLDocument;
                        if (htmlDoc != null)
                        {
                            #region FILL DEFAULT
                            //for (int i = 0; i < messages.Count; i++)
                            //for(int i = 0; i < msgs.Length; i++)
                            //{
                            //    if (msgs[i + 2] == "")
                            //    {
                            //        continue;
                            //    }
                            //    mshtml.IHTMLElementCollection inputs = htmlDoc2.getElementsByName(messages[i].ToString());
                            //    //int n = inputs.length;

                            //    mshtml.HTMLInputElement temp = inputs.item(0, 0) as mshtml.HTMLInputElement;
                            //    String type = temp.getAttribute("type", 0).ToString();
                            //    if (type == "text" || type == "password")
                            //    {
                            //        temp.setAttribute("value", msgs[i + 2], 0);
                            //    }
                            //}
                            #endregion
                            for (int i = 3; i < msgs.Length; i++)
                            {
                                if (msgs[i] == "")
                                {
                                    continue;
                                }
                                String[] msg_values = msgs[i].Split(':');

                                mshtml.IHTMLElementCollection inputs = htmlDoc2.getElementsByName(msg_values[0]);
                                //int n = inputs.length;

                                mshtml.HTMLInputElement temp = inputs.item(0, 0) as mshtml.HTMLInputElement;
                                String type = temp.getAttribute("type", 0).ToString();
                                if (type == "text" || type == "password")
                                {
                                    temp.setAttribute("value", msg_values[1], 0);
                                    temp.focus();
                                }                                
                            }
                            if (isSubmit)
                            {
                                mshtml.IHTMLElementCollection forms = htmlDoc2.getElementsByTagName("form");
                                for (int i = 0; i < forms.length; i++)
                                {
                                    mshtml.HTMLFormElement form = forms.item(i, i) as mshtml.HTMLFormElement;                                    
                                    if (form.innerText.ToLower().Contains("password"))
                                    {
                                        form.submit();
                                        break;
                                    }
                                }
                                //mshtml.IHTMLElementCollection inputs2 = htmlDoc2.getElementsByTagName("input");

                                //MessageBox.Show(inputs2.length.ToString());

                                //for (int i = 0; i < inputs2.length; i++)
                                //{
                                //    mshtml.HTMLInputElement input = inputs2.item(i, i) as mshtml.HTMLInputElement;
                                //    if (input.getAttribute("type",0).ToString() == "submit")
                                //    {
                                //        MessageBox.Show(input.value);
                                //        input.click();
                                //    }
                                //}
                                
                                
                            }
                        }
                    }
                    

                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();                    
                }
                catch (ArgumentNullException ane)
                {
                    MessageBox.Show(ane.ToString());
                    //Console.WriteLine("ArgumentN1ullException: {0}", ane.ToString());
                }
                catch (SocketException se)
                {
                    MessageBox.Show(se.ToString());
                    Console.WriteLine("SocketException: {0}", se.ToString());
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                    Console.WriteLine("Unknown exception: {0}", e.ToString());
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                Console.WriteLine("Exception: {0}", e.ToString());
            }
        }

        
    }
}
